// 独立文件，用于存储axios相关代码

// 导入Vue模块，需要另行独立引入Vue
import {createApp} from 'vue'
// 导入axios模块
import App from './App.vue'
import axios from 'axios'
import {ElMessage} from 'element-plus'
import router from "./router/router";
// 配置公共根地址(线上地址)
// axios.defaults.baseURL = 'http://ttapi.research.itcast.cn/'

createApp(App).config.globalProperties.$http = axios
// 请求拦截器
axios.interceptors.request.use(function (config) {
    // 发送请求的相关逻辑
    let userinfo = window.localStorage.getItem('tk')
    console.log(userinfo)
    // 判断token存在再做配置
    if (userinfo) {
        config.headers.tk = userinfo.replaceAll("\"","")
    }
    return config
}, function (error) {
    return Promise.reject(error)
})

axios.interceptors.response.use(function (config) {
    console.log(config.status)
    return config
},function (err) {
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.message = '请求错误'
                break
            case 401:
                console.log("wda")
                if (router.currentRoute.value.path.indexOf('/login')!==-1){
                    ElMessage.error({
                        showClose: true,
                        message: JSON.stringify("用户名或密码错误"),
                        center: true,
                    })
                }else {
                    router.push({name:'login'})
                }

                err.message = '未授权，请登录'
                break
            case 403:
                err.message = '拒绝访问'
                break

            case 404:
                err.message = `请求地址出错: ${err.response.config.url}`
                break

            case 408:
                err.message = '请求超时'
                break

            case 500:
                err.message = '服务器内部错误'
                break

            case 501:
                err.message = '服务未实现'
                break

            case 502:
                err.message = '网关错误'
                break

            case 503:
                err.message = '服务不可用'
                break

            case 504:
                err.message = '网关超时'
                break

            case 505:
                err.message = 'HTTP版本不受支持'
                break

            default:
        }
    }

    return Promise.reject(err)
})
